package edu.ccut.saturn.manager.dict.core;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IDataDictTypeInfo;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnDictionaryManager;

public class AddDictType extends DefaultComponent {

	private static final String QUERY_SQL = "select * from saturn_dict_type where type = ?";
	private static final String BNTYPE_INSERT_SQL = "INSERT INTO saturn_dict_type (type,name) VALUES(?,?)";

	@Override
	public void execute(IParameterContext parameterContext) throws Exception {

		String type = (String) parameterContext.getParameterValue(0);
		String name = (String) parameterContext.getParameterValue(1);
		
		String  addSucc = "false";
		
		PreparedStatement preStatement = null;
		ResultSet rs = null;
		try {
			preStatement = parameterContext.getConnection().prepareStatement(
					QUERY_SQL);
			preStatement.setString(1, type);
			rs = preStatement.executeQuery();
			if (!rs.next()) {
				preStatement = parameterContext.getConnection()
						.prepareStatement(BNTYPE_INSERT_SQL);
				preStatement.setString(1, type);
				preStatement.setString(2, name);
				preStatement.executeUpdate();
				addSucc = "true";
			}
		} catch (Exception e) {
			logger.error("found exception when execute Component Node "
					+ this.getComponentFullKey(), e);
		} finally {
			if (rs != null) {
				rs.close();
			}
			if (preStatement != null) {
				preStatement.close();
			}
		}
		
		if("true".equals(addSucc)) {
			Map<String, IDataDictTypeInfo> dictInfos = SaturnDictionaryManager.getInstance().getDictInfos();

			IDataDictTypeInfo newDataDictTypeInfo = SaturnDictionaryManager
					.getInstance().CreatDataDictTypeInfo();

			newDataDictTypeInfo.setType(type);
			newDataDictTypeInfo.setName(name);
			dictInfos.put(type ,newDataDictTypeInfo);
		}
		
		parameterContext.setParameter(2, addSucc);
		
	}
}
